/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-01-08 19:50:41
 * @LastEditors: weijingjing 1838352147@qq.com
 * @LastEditTime: 2025-01-08 21:36:21
 * @FilePath: /ocr-ui/src/component/WordDocumentRender.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useRef, useEffect, useState } from "react";
import mammoth from "mammoth";
const WordDocumentRenderer = ({ documentUrl }) => {
  const canvasRef = useRef(null);
  const [visibleArea, setVisibleArea] = useState({ top: 0, bottom: 0 });
  const [paragraphs, setParagraphs] = useState([]);
  const [tables, setTables] = useState([]);
  const [images, setImages] = useState([]);
  const [htmlContent,setHtmlContent]= useState('')

  const parseFile = ()=>{
    return new Promise((resolve, reject) => {
      let file=documentUrl
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onload = (e) => {
        console.log(e,">>>e?.target?.result")
        const arrayBuffer = e?.target?.result;
        // console.log(arrayBuffer,">>>data")
        mammoth.convertToHtml({ arrayBuffer:new Uint8Array(arrayBuffer)}).then((r) => {
          resolve(r.value);
        });
      };
    });
  }

  const parseHtml = async()=>{
    const content = await parseFile();
    console.log(content,">>>content")
    content&&setHtmlContent(content)
  }
  async function renderWordDocument() {
    try {
      console.log(documentUrl,">>>documentUrl")
      // const response = await fetch(documentUrl);
      const arrayBuffer = await parseFile();
      // console.log(blob,">>>blob")
      const { paragraphStyles, tables, images } = await mammoth.convertToHtml({
        arrayBuffer: arrayBuffer,
      });
      console.log(paragraphStyles,">>>paragraphStyles")
      // const { paragraphStyles, tables, images } = await mammoth.convertToHtml({
      //   path: documentUrl,
      // });

      // 处理段落信息
      // const paragraphsData = paragraphStyles.map((paragraph) => ({
      //   text: paragraph.children[0].text,
      //   style: paragraph.styleId,
      //   fontSize: paragraph.fontSize,
      //   fontFamily: paragraph.fontFamily,
      //   x: paragraph.x,
      //   y: paragraph.y,
      //   alignment: paragraph.alignment,
      //   lineSpacing: paragraph.lineSpacing,
      // }));
      // setParagraphs(paragraphsData);

      // // 处理表格信息
      // const tablesData = tables.map((table) => ({
      //   rows: table.rows.map((row) => ({
      //     cells: row.cells.map((cell) => ({
      //       text: cell.children[0].text,
      //       formatting: {
      //         borders: cell.formatting.borders,
      //         shading: cell.formatting.shading,
      //       },
      //     })),
      //   })),
      //   x: table.x,
      //   y: table.y,
      //   cellWidth: table.columnWidths[0],
      //   rowHeight: table.rowHeights[0],
      //   formatting: table.formatting,
      // }));
      // setTables(tablesData);

      // // 处理图像信息
      // const imagesData = images.map((image) => ({
      //   src: image.read,
      //   x: image.position.x,
      //   y: image.position.y,
      //   width: image.position.width,
      //   height: image.position.height,
      //   formatting: image.formatting,
      // }));
      // setImages(imagesData);
    } catch (error) {
      console.error("Error rendering Word document:", error);
    }
  }

  useEffect(() => {
    // const canvas = canvasRef.current;
    // if (!canvas) return;

    // const ctx = canvas.getContext("2d");
    // if (!ctx) return;

    parseHtml();

    // const handleScroll = () => {
    //   setVisibleArea({
    //     top: canvas.scrollTop,
    //     bottom: canvas.scrollTop + canvas.height,
    //   });
    // };

    // canvas.addEventListener("scroll", handleScroll);

    // return () => {
    //   canvas.removeEventListener("scroll", handleScroll);
    // };
  }, [documentUrl]);

  // useEffect(() => {
  //   const canvas = canvasRef.current;
  //   const ctx = canvas.getContext("2d");

  //   // 清空画布
  //   ctx.clearRect(0, 0, canvas.width, canvas.height);

  //   // 渲染段落
  //   paragraphs
  //     .filter(
  //       (paragraph) =>
  //         paragraph.y >= visibleArea.top && paragraph.y <= visibleArea.bottom
  //     )
  //     .forEach((paragraph) => {
  //       ctx.font = `${paragraph.fontSize}px ${paragraph.fontFamily}`;
  //       ctx.textAlign = paragraph.alignment;
  //       ctx.fillText(paragraph.text, paragraph.x, paragraph.y);
  //     });

  //   // 渲染表格
  //   tables
  //     .filter(
  //       (table) =>
  //         table.y >= visibleArea.top &&
  //         table.y + table.rowHeight * table.rows.length <= visibleArea.bottom
  //     )
  //     .forEach((table) => {
  //       table.rows.forEach((row, rowIndex) => {
  //         row.cells.forEach((cell, cellIndex) => {
  //           ctx.font = "12px Arial";
  //           ctx.fillText(
  //             cell.text,
  //             table.x + cellIndex * table.cellWidth,
  //             table.y + rowIndex * table.rowHeight
  //           );
  //           // 渲染单元格边框和背景
  //           ctx.strokeRect(
  //             table.x + cellIndex * table.cellWidth,
  //             table.y + rowIndex * table.rowHeight,
  //             table.cellWidth,
  //             table.rowHeight
  //           );
  //           ctx.fillStyle = cell.formatting.shading.fill;
  //           ctx.fillRect(
  //             table.x + cellIndex * table.cellWidth,
  //             table.y + rowIndex * table.rowHeight,
  //             table.cellWidth,
  //             table.rowHeight
  //           );
  //           ctx.fillStyle = "black"; // 重置填充颜色
  //         });
  //       });
  //     });

  //   // 渲染图像
  //   images.forEach((image) => {
  //     const img = new Image();
  //     img.src = image.src;
  //     ctx.drawImage(img, image.x, image.y, image.width, image.height);
  //   });
  // }, [paragraphs, tables, images, visibleArea]);

  return <div className="doc-html" dangerouslySetInnerHTML={{ __html: htmlContent }}></div>;
};

export default WordDocumentRenderer;
